import {RemoteStorage} from "./storage";
import {IParams} from "./params";
import * as step from '@ali/flow-step-toolkit'
import fs from "fs";
import {CACHE_FILE_MAX_SIZE} from "./cache";

export async function download(remoteStorage: RemoteStorage, params: IParams, artifactFullName: string): Promise<void> {
    const existed = await remoteStorage.stat(params.fileID)
    if (!existed) {
        step.infoV1(`cache ${params.fileID} not exist skip...`);
        return

    }
    step.infoV1(`fetch cache file ${params.fileID} -> ${artifactFullName}`);

    const result = await remoteStorage.get(params.fileID, artifactFullName)
    if (result.res.status == 200) {
        step.infoV1("fetch cache successfully");
    } else {
        step.errorV1("failed to fetch cache")
    }

    const stats = fs.statSync(artifactFullName)
    const cacheFileSize = stats.size;
    step.infoV1(`${artifactFullName} size ${cacheFileSize}`);
    if (cacheFileSize > CACHE_FILE_MAX_SIZE) {
        step.warnV1(`${artifactFullName} size ${cacheFileSize} exceeding max size limit ${CACHE_FILE_MAX_SIZE}, will abort upload.`);
    }

    step.infoV1(`begin recover cache folder`);

    // TODO command tar only support in linux/darwin , use other tool in windows
    let platform = step.platform.getPlatform();
    if (platform !== step.platform.PLATFORM_LINUX && platform !== step.platform.PLATFORM_DARWIN) {
        throw new Error(`cache download in ${platform} not implemented now`);
    }

    const resultCode = await step.exec.call("/bin/bash", ["-c", `tar -zxvf ${artifactFullName} -C / >/dev/null`], {
        listener: {
            stdoutLine: (line: string) => step.infoV1(line),
            stderrLine: (line: string) => step.warnV1(line),
        }
    });

    step.infoV1(`finish recover cache folder resultCode: ${resultCode}`);
}